clc; clearvars; close all;
addpath('CEC2010\')
addpath('CEC2010\datafiles\');
addpath('CEC2010\javarandom\bin\');
addpath('CEC2010\javarandom\src\');
truegroup = load('f14_opm.mat', 'p');
truegroup = truegroup.p;
global initial_flag

NS = 100;   % 种群数
dim = 1000;   % 种群维度
upperBound = [100, 5, 32, 100, 5, 32, 100, 100, 100, 5, 32, 100, 100, 100, 5, 32, 100, 100, 100, 100];
lowerBound = [-100, -5, -32, -100, -5, -32, -100, -100, -100, -5, -32, -100, -100, -100, -5, -32, -100, -100, -100, -100];
bestYhistory = [];    % 保存每次迭代的最佳值

matrix = zeros(dim, dim);   % 真实变量之间的关系矩阵
for i0 = 1 : 20
    start = (i0 - 1) * 50 + 1;
    Ends = i0 * 50;
    for i2 = start : Ends
        for i3 = (i2 + 1) : Ends
            matrix(truegroup(i2), truegroup(i3)) = 1;
            matrix(truegroup(i3), truegroup(i2)) = 1;
        end
    end
end

matrix1 = zeros(dim, dim);      % 辅助查找行号列号矩阵
ss = 1;
for i5 = 1 : dim
    for i6 = (i5 + 1) : dim
        matrix1(i5, i6) = ss;
        ss = ss + 1;
    end
end
sumA = dim * (dim - 1) / 2;
Aintr = randperm(sumA);
pr = ceil(0.2 * sumA);
Prior = Aintr(1 : pr);
priormatrix = zeros(dim, dim);      % 部分交互变量之间的关系矩阵
for i4 = 1 : pr
    A = Prior(i4);
    [row, col] = find(matrix1 == A);
    priormatrix(row, col) = matrix(row, col);
    priormatrix(col, row) = matrix(col, row);
end
groupInfor=CellG(priormatrix,1);
s = size(groupInfor, 1);   % 子控件数目

for funcNum = 14

    initial_flag = 0;    % 换一个函数initial_flag重置为0
    sampleX = lhsdesign(NS, dim) .* (upperBound(funcNum) - lowerBound(funcNum)) + lowerBound(funcNum) .* ones(NS, dim);    % 生成NS个种群,并获得其评估值
    lastSampleX = sampleX;
    sampleY = benchmark_func(sampleX, funcNum);
    [bestY, bestIndex] = min(sampleY);    % 获取全局最小值以及对应的种群
    lastBestY = bestY;
    bestX = sampleX(bestIndex, :);
    bestYhistory = [bestYhistory; bestY];
    evalue = 60;

    while evalue < 3 * 10 ^ 6     
        for i1 = 1 : s
            group = groupInfor{i1};
            dim = size(group,2);
            NPi = dim + 10;
            Geni = dim + 5;
            index = randperm(NS);
            subX = sampleX(index(1:NPi), group);
            [subX, subY] = JADE(subX, sampleY(index(1:NPi)), bestX, group, Geni, dim, lowerBound(funcNum), upperBound(funcNum), @(x)benchmark_func(x, funcNum));
            evalue = evalue + NPi * Geni;
            sampleX(index(1:NPi), group) = subX;
            sampleY(index(1:NPi)) = benchmark_func(sampleX(index(1:NPi), :), funcNum);   
            evalue = evalue + NPi;
            [bestY, bestIndex] = min(sampleY);    % 获取全局最小值以及对应的种群
            bestX = sampleX(bestIndex, :);
        end
        bestYhistory = [bestYhistory; bestY];
        fprintf('evalue:%d\n', evalue);
    end
end
plot(bestYhistory);
save('20%bestYhistory.mat','bestYhistory');